package com.example.nio.security.custom;


import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

@Component
public class UnauthorizedEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        HttpServletRequest hsrt = (HttpServletRequest)request;
        String url = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest)request).getContextPath().length());
        if(url.contains("/api/") || isAjaxRequest(request)) {
            //返回401
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,authException.getMessage());
            //返回Json
//                response.setContentType("application/json;charset=utf-8");
//                PrintWriter out = response.getWriter();
//                StringBuffer sb = new StringBuffer();
//                sb.append("{\"status\":\"error\",\"msg\":\"");
//
//                sb.append("未登陆!");
//
//                sb.append("\"}");
//                out.write(sb.toString());
//                out.flush();
//                out.close();

        }else{
            response.sendRedirect(hsrt.getContextPath()+"/toLogin");
        }
    }

    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxFlag = request.getHeader("X-Requested-With");
        return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);
    }
}
